package com.geen.tuoke.ui.activity

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import androidx.activity.OnBackPressedCallback
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.blankj.utilcode.util.FileIOUtils
import com.geen.tuoke.R
import com.geen.tuoke.base.BaseActivity
import com.geen.tuoke.base.EmptyViewModel
import com.geen.tuoke.databinding.ActivityMainBinding
import com.geen.tuoke.network.utils.CacheUtil
import com.geen.tuoke.ui.fragment.PhoneFragment
import com.geen.tuoke.ui.fragment.FragmentHome
import com.geen.tuoke.ui.fragment.FragmentMe
import com.geen.tuoke.ui.viewmodel.MainViewModel
import com.geen.tuoke.utils.AppManager
import com.geen.tuoke.utils.AppUtil
import com.geen.tuoke.utils.EventCode
import com.geen.tuoke.utils.LogUtils
import com.geen.tuoke.utils.ext.checkAppPermission
import com.geen.tuoke.utils.ext.launch
import com.geen.tuoke.utils.ext.startActivity
import com.geen.tuoke.utils.ext.toastShort
import com.geen.tuoke.widget.HomePagerAdapter
import com.geen.tuoke.widget.SpecialTab
import com.geen.tuoke.widget.SpecialTabRound
import com.kbeanie.multipicker.api.entity.ChosenImage
import com.kbeanie.multipicker.utils.FileUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
import me.majiajie.pagerbottomtabstrip.NavigationController
import me.majiajie.pagerbottomtabstrip.item.BaseTabItem
import java.io.*
import java.lang.Exception


class MainActivity : BaseActivity<MainViewModel, ActivityMainBinding>() {

    private var exitTime :Long = 0

    override fun getLayoutId(): Int {
        return R.layout.activity_main
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        with(mBinding) {
            lifecycleOwner = this@MainActivity
        }
        initTab()
        checkAppPermission {

        }

        mViewModel.takePicture.observe(this, {
            if (it) {
                pickImageFromCamera()
            }
        })

        onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                if (System.currentTimeMillis() - exitTime > 2000) {
                    toastShort("再按一次退出程序")
                    exitTime = System.currentTimeMillis()
                } else {
                    finish()
                }
            }
        })
    }

    override fun onImagesChosen(p0: MutableList<ChosenImage>?) {
        super.onImagesChosen(p0)
        p0?.let {
            val pickImagePath = it[0].originalPath
            mViewModel.uploadFile("1111", pickImagePath, uploadCallBack = {
                toastShort("上传成功")
            })
        }
    }

    private fun initTab() {
        val navigationView = mBinding.mNavigation.custom()
            .addItem(newItem(R.mipmap.icon_custom_normal, R.mipmap.icon_custom_select, "首页"))
            .addItem(newRoundItem(R.mipmap.icon_call_phone, R.mipmap.icon_call_phone, ""))
            .addItem(newItem(R.mipmap.icon_me_normal, R.mipmap.icon_me_select, "我的"))
            .build() as NavigationController

        navigationView.addSimpleTabItemSelectedListener { index, old ->
            LogUtils.debugInfo("tab" + index + "---" + old)
            if (index == 2) {
                if (CacheUtil.getUserInfo() == null) {
                    mViewModel.refreshUserInfo(true)
                    mBinding.viewPager.currentItem = old
                }
            }
        }

        val fragmentList = arrayListOf<Fragment>()
        fragmentList.add(FragmentHome())
        fragmentList.add(PhoneFragment())
        fragmentList.add(FragmentMe())
        val mAdapter = HomePagerAdapter(supportFragmentManager, fragmentList)
        mBinding.viewPager.adapter = mAdapter
        mBinding.viewPager.offscreenPageLimit = fragmentList.size
        navigationView.setupWithViewPager(mBinding.viewPager)
        mBinding.viewPager.currentItem = 1
    }

    /**
     * 正常tab
     */
    private fun newItem(drawable: Int, checkedDrawable: Int, text: String): BaseTabItem {
        val mainTab = SpecialTab(this)
        mainTab.initialize(drawable, checkedDrawable, text)
        mainTab.setTextDefaultColor(ContextCompat.getColor(this, R.color.black))
        mainTab.setTextCheckedColor(ContextCompat.getColor(this, R.color.select_tab_color))
        return mainTab
    }

    /**
     * 圆形tab
     */
    private fun newRoundItem(drawable: Int, checkedDrawable: Int, text: String): BaseTabItem {
        val mainTab = SpecialTabRound(this)
        mainTab.initialize(drawable, checkedDrawable, text)
        mainTab.setTextDefaultColor(ContextCompat.getColor(this, R.color.black))
        mainTab.setTextCheckedColor(ContextCompat.getColor(this, R.color.select_tab_color))
        return mainTab
    }

    override fun onEventCome(eventCode: String) {
        super.onEventCome(eventCode)
        when (eventCode) {
            EventCode.EVENT_TOKEN_ERROR -> {
                toastShort("暂未登录或登录已经过期，请重新登录")
                //跳转登陆页
                AppManager.appManager?.finishAllActivity()
                startActivity<LoginActivity>()
            }
            else -> {

            }
        }
    }

    override fun onRestart() {
        super.onRestart()
        when(mBinding.viewPager.currentItem){
            0->{
                mViewModel.tabHomeRestart.value = true
            }
            1->{
                mViewModel.tabPhoneRestart.value = true
            }
        }
    }

}